package org.linloong.modules.apis.disease.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.linloong.config.audio.DifyAgentProperties;
import org.linloong.core.result.Result;
import org.linloong.modules.apis.disease.entity.DiseaseChatHistory;
import org.linloong.modules.apis.disease.service.IDiseaseChatHistoryService;
import org.linloong.modules.apis.fire.dto.AudioChatRequest;
import org.linloong.utils.DifyAgentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @Package: org.linloong.modules.apis.disease.controller.DiseaseChatHistoryController
 * @Author: guxin
 * @CreateTime: 2025/10/19 17:45
 * @Description: 病虫害检测记录 前端控制器
 * @Version: 3.0
 */
@Slf4j
@RestController
@RequestMapping("/api/disease/chat/history")
@RequiredArgsConstructor
@Tag(name = "病虫害-聊天记录")
@ApiSupport(order = 203)
public class DiseaseChatHistoryController {

    @Autowired
    private DifyAgentProperties agentProperties;
    @Autowired
    private IDiseaseChatHistoryService diseaseChatHistoryService;

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    @ApiOperationSupport(order = 1)
    public Result<String> upload(@RequestParam(value = "file") MultipartFile file) {
        return Result.success(DifyAgentUtil.uploadFile(file, agentProperties, agentProperties.getDiseaseAuth()));
    }

    @PostMapping("/chat")
    @Operation(summary = "聊天")
    @ApiOperationSupport(order = 2)
    public void sendMessage(@Valid @RequestBody AudioChatRequest request, HttpServletResponse response) {
        log.info("收到聊天请求: {}", request.getQuery());
        // 设置响应头以支持事件流
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        DifyAgentUtil.chat(request, response, agentProperties, agentProperties.getDiseaseAuth());
    }

    @GetMapping("/variables/{conversationId}")
    @Operation(summary = "获取对话变量")
    @ApiOperationSupport(order = 3)
    public Result variables(@PathVariable String conversationId) {
        return Result.success(DifyAgentUtil.getVariables(conversationId, agentProperties, agentProperties.getDiseaseAuth()));
    }

    @PostMapping("/save/{conversationId}")
    @Operation(summary = "保存或更新聊天记录")
    @ApiOperationSupport(order = 4)
    public Result<Boolean> save(@PathVariable String conversationId) {
        JSONArray messages = DifyAgentUtil.getMessages(conversationId, agentProperties, agentProperties.getDiseaseAuth());
        if (CollectionUtils.isEmpty(messages)) {
            return Result.fail("未找到对应聊天记录");
        }
        DiseaseChatHistory history = diseaseChatHistoryService.getOne(new QueryWrapper<>(new DiseaseChatHistory().setConversationId(conversationId)));
        if (history == null) {
            history = new DiseaseChatHistory();
            history.setConversationId(conversationId);
            history.setContent(messages);
            history.setTimestamp(LocalDateTime.now());
            diseaseChatHistoryService.save(history);
            return Result.success(true);
        }
        history.setContent(messages);
        diseaseChatHistoryService.updateById(history);
        return Result.success(true);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除聊天记录")
    @ApiOperationSupport(order = 5)
    public Result<Boolean> remove(@PathVariable Long id) {
        return Result.success(diseaseChatHistoryService.removeById(id));
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询聊天记录")
    @ApiOperationSupport(order = 6)
    public Result page(@Parameter(description = "当前页码，从1开始") Integer page,
                       @Parameter(description = "每页显示记录数") Integer limit) {
        try (Page<T> ignored = PageHelper.startPage(page, limit)) {
            return Result.success(
                    new PageInfo<>(
                            diseaseChatHistoryService.list(
                                    new QueryWrapper<>(new DiseaseChatHistory())
                                            .orderByDesc("timestamp")
                            )
                    )
            );
        }
    }

    @PostMapping("/send/wx/{conversationId}")
    @Operation(summary = "发送微信消息")
    @ApiOperationSupport(order = 7)
    public Result<Boolean> sendWxMessage(@PathVariable String conversationId) {
        JSONArray variables = DifyAgentUtil.getVariables(conversationId, agentProperties, agentProperties.getDiseaseAuth());
        Optional<Object> ticketInfo = variables.stream()
                .filter(variable -> "ticket_info".equals(((JSONObject) variable).getString("name")))
                .findFirst();
        if (ticketInfo.isEmpty()) {
            return Result.fail("未找到消息内容");
        }
        JSONObject value = JSON.parseObject(((JSONObject) ticketInfo.get()).getString("value"));
        DiseaseChatHistory history = diseaseChatHistoryService.getOne(new QueryWrapper<>(new DiseaseChatHistory().setConversationId(conversationId)));
        long wordId = history == null ? IdWorker.getId() : history.getId();
        wordId = DifyAgentUtil.getWordCache(value.getString("document_link"), wordId);
        if (wordId == 0) {
            return Result.fail("未获取到报告");
        }
        String documentLink = agentProperties.getWordLinkPath() + wordId;
        String content = String.format("高峰林场%s林班%s小班检测到%s病害，请安排处理。病害分析报告为 %s。",
                value.getString("compartment"), value.getString("subcompartment"), value.getString("disease"), documentLink);
        log.info("消息内容：{}", content);
        return Result.success(DifyAgentUtil.sendWxMessage(content, agentProperties, agentProperties.getWxAuth()));
    }
}
